<template>
  <div class="app-redirect">
    <a-skeleton active/>
  </div>
</template>

<script>
import {mapState} from 'vuex'

export default {
  name: 'LowAppRedirect',
  computed: {
    ...mapState({
      menuList: state => state.lowApp.menuList,
      initialed: state => state.lowApp.initialed,
    }),
  },
  created() {
    if (this.initialed) {
      this.next(this.menuList)
    } else {
      this.asyncNext()
    }
  },
  methods: {
    next(menuList) {
      let option = {
        query: this.$route.query,
        params: this.$route.params,
      }
      if (menuList.length === 0) {
        this.nextToHome(option)
      } else {
        let routerLink = this.getRouterLink(menuList)
        if (routerLink == null) {
          this.nextToHome(option)
        } else {
          this.$router.replace({...option, path: routerLink})
        }
      }
    },
    // 跳转到首页，并且启用开发模式
    async nextToHome(option) {
      await this.$store.dispatch('setLowAppDevMode', true)
      await this.$router.replace({...option, name: 'low-app-@appId'})
    },
    // 等待菜单加载完成进行下一步
    asyncNext() {
      let fn = (callback) => {
        setTimeout(() => {
          if (this.initialed) {
            callback()
          } else {
            fn(callback)
          }
        }, 10)
      }
      fn(() => this.next(this.menuList))
    },
    // 获取第一个菜单的地址，如果是分组就获取分组里的第一个，如果第一个分组没有菜单，就顺移一位
    getRouterLink(menuList) {
      let fn = (idx) => {
        if (idx >= menuList.length) {
          return null
        }
        let item = menuList[idx]
        if (item.type === 'group') {
          if (item.children && item.children.length > 0) {
            return item.children[0].routerLink
          } else {
            return fn(idx + 1)
          }
        } else {
          return item.routerLink
        }
      }
      return fn(0)
    },
  },
}
</script>

<style scoped>
.app-redirect {
  height: 70vh;
  background-color: #fefefe;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
}
</style>